<?php

namespace app\api\controller;

use app\common\BaseHelper;

use app\admin\model\Userproject as UserprojectMdl;
use app\admin\model\Userprojecttask;
use app\admin\model\Userprojectfile;
use app\admin\model\Userprojectmember;
use app\admin\model\User;
use app\admin\model\Member;
use app\admin\model\Image;

use think\Db;
use think\Exception;
use think\Request;

class Userproject extends BaseController
{

    /**
     * 首页
     */
    public function getHome()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $userId = $param->userId;
        $where = [
            'userId' => $userId,
            'isDelete' => 2
        ];
        if(!empty($param->keyword)){
            $where['name'] = ['like', '%' . $param->keyword . '%'];
        }

        $model = new UserprojectMdl();
        if ($param->type == 1) {
            // 我创建的
            $fields = '*';
            $order = 'isTop ASC, topTime DESC, createDate DESC';
            $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
            $total = $model->where($where)->count();
        } else {
            // 我执行的
            $ids = Userprojecttask::where('executor', $userId)->column('projectId');
            $where = [
                'id' => ['in', $ids],
                'isDelete' => 2
            ];
            $fields = '*';
            $order = 'isTop ASC, topTime DESC, createDate DESC';
            $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
            $total = $model->where($where)->count();
        }

        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关数据');
        }

        foreach ($result as $item) {
            // 总任务数
            $totalTask = Userprojecttask::where(['projectId' => $item['id']])->count();
            $item['totalTask'] = $totalTask;
            // 已完成任务数
            $completeTask = Userprojecttask::where(['projectId' => $item['id'], 'status' => ['in', '1,2']])->count();
            $item['completeTask'] = $completeTask;
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 创建工程项目
     */
    public function createProject()
    {
        $param = self::getHttpParam();

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->name)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '项目名(name) 不能为空');
        }

        $userId = $param->userId;

        $data = (array)$param;
        $model = new UserprojectMdl();
        $data['id'] = BaseHelper::getUUID();
        $data['createDate'] = time();

        $result = $model->save($data);

        if($result === false){
            return show(config('status.ERROR_STATUS'), '创建失败', $model->getError());
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, []);
    }

    /**
     * 操作工程项目
     */
    public function handleProject()
    {
        $param = self::getHttpParam();

        if (empty($param->projectId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'projectId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2, 3])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }

        $where = [
            'id' => $param->projectId
        ];
        $model = new UserprojectMdl();
        if ($param->type == 1) {
            // 置顶
            $result = $model->where($where)->update(['isTop' => 1, 'topTime' => time()]);
        } elseif ($param->type == 2) {
            // 取消置顶
            $result = $model->where($where)->update(['isTop' => 2, 'topTime' => '']);
        } else {
            // 删除
            $result = $model->where($where)->update(['isDelete' => 1]);
        }

        if($result === false){
            return show(config('status.ERROR_STATUS'), '操作失败', $model->getError());
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, []);
    }

    /**
     * 项目成员
     */
    public function getMembers()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->projectId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'projectId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $projectId = $param->projectId;
        $where = [
            'projectId' => $projectId
        ];

        //$model = new Userprojectmember();
        $model = new Userprojecttask();
        $fields = 'executor';
        $order = 'createDate DESC';
        $list = $model->where($where)->group('executor')->field($fields)->limit($start, $length)->order($order)->select();
        $total = $model->where($where)->count();
        if (!$list) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关数据');
        }
        $members = [];
        foreach ($list as $member) {
            //// 是否已有该数据，即一个人有多个任务
            $userInfo = User::where(['id' => $member['executor']])->field('id as userId, memberId, nickName as name, avatarUrl as avatar')->find();
            if($userInfo['memberId']){
                $userInfo = Member::where(['id' => $userInfo['memberId']])->field('userId, name, avatar, job, institutionJob, villageJob')->find();
            }
            $members[] = $userInfo;
        }

        $userproject = UserprojectMdl::where(['id' => $projectId])->field('userId')->find();
        $managers = User::where(['id' => $userproject['userId']])->field('id as userId, memberId, nickName as name, avatarUrl as avatar')->find();
        if($managers['memberId']){
            $managers = Member::where(['id' => $managers['memberId']])->field('userId, name, avatar, job, institutionJob, villageJob')->find();
        }

        $data = [
            'managers' => $managers ? : 0,
            'members' => $members ? : '',
            'total' => $total ? : 0,
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

}